package com.smartum.mpr.client.presenter;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.StatusCodeException;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.IButton;
import com.smartum.mpr.client.Authorization;
import com.smartum.mpr.client.event.LoginEvent;
import com.smartum.mpr.client.event.LogoutButtonHandler;
import com.smartum.mpr.client.services.UserService;
import com.smartum.mpr.client.services.UserServiceAsync;
import com.smartum.mpr.client.utils.HistoryHelper;
import com.smartum.mpr.client.view.MaskPanel;
import com.smartum.mpr.shared.User;

/**
 * Presenter class for header widget.
 */
public class HeaderPresenter implements Presenter {

    public interface Display {
        Widget getHeaderWidget();

        IButton getLogout();

        Canvas getUserName();
    }

    private final Display display;
    private HandlerManager eventBus;

    public HeaderPresenter(Display display, HandlerManager eventBus) {
        this.display = display;
        this.eventBus = eventBus;
    }

    public void go(HasWidgets container) {
        container.clear();

        final Authorization authorizationBundle = com.google.gwt.core.shared.GWT.create(Authorization.class);
        final MaskPanel maskPanel = new MaskPanel();
        maskPanel.show();

        final UserServiceAsync userServiceAsync = GWT.create(UserService.class);
        userServiceAsync.retrieveUserFromSesion(new AsyncCallback<User>() {
            public void onFailure(Throwable caught) {
                maskPanel.hide();
                HistoryHelper.navigateToken(HistoryHelper.LOGIN_TOKEN);
            }

            public void onSuccess(User result) {
                maskPanel.hide();
                DOM.getElementById("logoImage").getStyle().setVisibility(Style.Visibility.VISIBLE);
                display.getUserName().setContents(authorizationBundle.welcome() + result.getName());
            }
        });

        container.add(this.display.getHeaderWidget());
    }

    public void bind() {
        this.display.getLogout().addClickHandler(new LogoutButtonHandler());
    }

    public HandlerManager eventBus() {
        return this.eventBus;
    }
}
